package com.franklin.java.api.psi.data.resolver;

import com.franklin.java.api.psi.data.PsiData;
import com.franklin.java.utils.PsiUtils;
import com.intellij.psi.*;
import com.intellij.psi.util.PsiTreeUtil;
import org.apache.commons.lang3.ArrayUtils;

import java.util.Arrays;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;


/**
 * @author Franklin
 * @since 2021/08/15/ 21:27
 */
public class ClassFieldResolver implements PsiDataResolver {
    @Override
    public PsiData resolve(String name, String value, PsiElement dataElement) {
        //从PsiClass中找
        PsiClass psiClass = PsiTreeUtil.getParentOfType(dataElement, PsiClass.class);
        if (Objects.nonNull(psiClass)) {
            PsiField[] fields = psiClass.getAllFields();
            if (ArrayUtils.isNotEmpty(fields)) {
                List<PsiField> psiFieldList = Arrays.stream(fields)
                        .filter(psiField -> psiField.getName().equals(name))
                        .collect(Collectors.toList());
                PsiData psiData = resolveVariable(dataElement, value, psiFieldList);
                if (Objects.nonNull(psiData)){
                    return psiData;
                }
            }
        }
        return null;
    }

    @Override
    public String getVariableDefaultType(PsiElement psiElement) {
        if (psiElement instanceof PsiField){
            PsiField psiField = (PsiField) psiElement;
            return psiField.getType().getPresentableText();
        }
        return "";
    }

    @Override
    public boolean isSuitableElement(PsiElement psiElement,String targetValue) {
        if (psiElement instanceof PsiField){
            PsiField psiField = (PsiField) psiElement;
            return psiField.getName().equals(targetValue);
        }
        return true;
    }
}
